package com.ixuestar.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import com.ixuestar.entity.ProbabilityEntity;

public class MyAlgorithmUtil {

	private MyAlgorithmUtil() {
    }

    /**
     * 概率性抽奖
     * @param probabilityEntityList  概率配置列表
     * @param defaultValue 不符条件返回的默认结果
     * @param <T> 抽奖的实体
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> ProbabilityEntity<T> probabilityLottery(List<ProbabilityEntity<T>> probabilityEntityList,ProbabilityEntity<T> defaultValue) {
    	// 公平性检测
        if (probabilityEntityList.stream().mapToDouble(e -> e.getProbabilityValue()).summaryStatistics().getSum() != 100.00) {
            System.out.println("概率总共不为1，公平性有偏差");
        }

        // 基数建立
        Map<String, Integer> numbers = new HashMap<>();
        for (ProbabilityEntity entity : probabilityEntityList) {
            numbers.put(entity.getId(), (int) (entity.getProbabilityValue() * 10.0));
        }
        // 基数分区
        int idxStart = 0;
        int idxEnd = 0;
        List<Integer> nums = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            nums.add(i);
        }
        Map<String, List<Integer>> numParts = new HashMap<>();
        for (Map.Entry<String, Integer> entry : numbers.entrySet()) {
            idxEnd = idxStart + entry.getValue();
            if (idxEnd >= 1000) {
                idxEnd = 1000;
            }
            if (entry.getValue() > 0) {
                numParts.put(entry.getKey(), nums.subList(idxStart, idxEnd));
            }
            idxStart = idxEnd;
        }
        // 随机抽取
        Random random = new Random();
        int r = random.nextInt(1000);
        // 基础概率数
        for (Map.Entry<String, List<Integer>> entry : numParts.entrySet()) {
            List<Integer> value = entry.getValue();
            if (value.contains(r)) {
                List<ProbabilityEntity> entities = probabilityEntityList.stream().filter(e -> e.getId().equals(entry.getKey())).collect(Collectors.toList());
                System.out.println("4"+entities);
                if (entities != null && entities.size() > 0) {
                    return entities.get(0);
                }
            }
        }
        return defaultValue;
    }
}
